package cn.itlight.basic.interceptor;


import cn.itlight.basic.annotation.PreAuthorize;
import cn.itlight.basic.jwt.JwtUtils;
import cn.itlight.basic.jwt.Payload;
import cn.itlight.basic.jwt.RsaUtils;
import cn.itlight.basic.jwt.UserInfo;
import cn.itlight.system.mapper.PermissionMapper;
import cn.itlight.user.domain.Logininfo;
import cn.itlight.user.domain.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @Description: 登录拦截器
* @Author: Mr.She
* @Version: 1.0
* @Date:  2022/6/13 16:54
*/
@Component // 需要加上此注解将当前登录拦截器交给spring管理
public class LoginInterceptor implements HandlerInterceptor {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;

    @Value("${jwt.rsa.pub}")
    private String rsaPublic;

//    /*
//    * @Title: preHandle
//    * @Description: token拦截器
//    * @Author: TomLiu
//    * @Version: 1.0
//    * @Date:  2022/7/14 16:47
//    * @Parameters:
//    * @Return
//    */
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        // 1.从请求头中获取token，判断是否存在
//        String token = request.getHeader("token");
//        // 设置编码字符集
//        response.setCharacterEncoding("UTF-8");
//        // 设置响应参数类型为JSON
//        response.setContentType("application/json;charset=UTF-8");
//        // 1.1.不存在，返回一个{"success":false,"message":"noLogin"},再返回false
//        if (!StringUtils.isEmpty(token)){
//            // 根据token获取到Redis中的用户信息
//            Object logininfo = redisTemplate.opsForValue().get(token);
//            if (logininfo != null){
//                // 判断是否是员工登录
//                Logininfo logininfoTmp = new Logininfo();
//                BeanUtils.copyProperties(logininfo, logininfoTmp);
//                if (logininfoTmp.getType() == 0){
//                    // 得到本次请求的方法对象
//                    HandlerMethod handlerMethod = (HandlerMethod) handler;
//                    // 拿到方法对象指定注解
//                    PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
//                    if(preAuthorize != null){
//                        // 从注解中获取到sn值，也就是本次请求对应的权限编码，用于判断用户是否有此URL权限
//                        String permissionSn = preAuthorize.sn();
//                        // 获取到用户所拥有的所有权限
//                        List<String> ownPermissions = permissionMapper.loadOwnPermissionByLogininId(logininfoTmp.getId());
//                        // 判断是否有权限
//                        if (!ownPermissions.contains(permissionSn)){
//                            PrintWriter writer = response.getWriter();
//                            writer.write("{\"success\":false,\"message\":\"noPermission\"}");
//                            writer.flush();
//                            writer.close();
//                            return false;
//                        }
//                    }
//
//                }
//                // 3.刷新token过期时间
//                redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
//                // 4.放行
//                return true;
//            }
//        }
//        PrintWriter writer = response.getWriter();
//        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
//        writer.flush();
//        writer.close();
//        return false;
//    }
//}

    /*
    * @Title: preHandle
    * @Description: jwt拦截器
    * @Author: TomLiu
    * @Version: 1.0
    * @Date:  2022/7/14 16:47
    * @Parameters:
    * @Return
    */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.从请求头中获取token，判断是否存在
        String token = request.getHeader("token");
        // 设置编码字符集
        response.setCharacterEncoding("UTF-8");
        // 设置响应参数类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        // 1.1.不存在，返回一个{"success":false,"message":"noLogin"},再返回false
        if (!StringUtils.isEmpty(token)){
            // 2 解析token里面内容
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(rsaPublic).getFile());
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            if (payload != null){
                // 1.判断是否是后台用户，如果是进入判断
                UserInfo userInfo = payload.getUserInfo();
                Logininfo logininfo = userInfo.getLogininfo();
                if (logininfo.getType() == 0){
                    // 得到本次请求的方法对象
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    // 拿到方法对象指定注解
                    PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                    if(preAuthorize != null){
                        // 从注解中获取到sn值，也就是本次请求对应的权限编码，用于判断用户是否有此URL权限
                        String permissionSn = preAuthorize.sn();
                        // 判断是否有权限
                        if (!userInfo.getPermissions().contains(permissionSn)){

                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"message\":\"noPermission\"}");
                            writer.flush();
                            writer.close();
                            return false;
                        }
                    }

                }
                // 3.刷新token过期时间
                redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
                // 4.放行
                return true;
            }
        }
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;
    }
}